package com.newshub.app.ui.search

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.newshub.app.data.model.News
import com.newshub.app.data.repository.NewsRepository
import kotlinx.coroutines.launch

class SearchViewModel : ViewModel() {
    
    private val newsRepository = NewsRepository
    
    private val _searchResults = MutableLiveData<List<News>>(emptyList())
    val searchResults: LiveData<List<News>> = _searchResults
    
    private val _isLoading = MutableLiveData<Boolean>(false)
    val isLoading: LiveData<Boolean> = _isLoading
    
    private val _error = MutableLiveData<String?>(null)
    val error: LiveData<String?> = _error
    
    fun searchNews(keyword: String, page: Int = 1) {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null
                
                newsRepository.searchNews(keyword, page)
                    .subscribe({
                        _searchResults.value = it
                        _isLoading.value = false
                        
                        // 如果没有搜索结果，设置错误消息
                        if (it.isEmpty()) {
                            _error.value = "没有找到相关新闻"
                        }
                    }, {
                        _error.value = it.message
                        _isLoading.value = false
                    })
            } catch (e: Exception) {
                _error.value = e.message
                _isLoading.value = false
            }
        }
    }
    
    fun toggleFavorite(news: News) {
        viewModelScope.launch {
            try {
                if (news.isFavorite) {
                    newsRepository.removeFromFavorite(news.docid)
                } else {
                    newsRepository.addToFavorite(news)
                }
                
                // 更新当前搜索结果中的收藏状态
                _searchResults.value = _searchResults.value?.map {
                    if (it.docid == news.docid) {
                        it.copy(isFavorite = !it.isFavorite)
                    } else {
                        it
                    }
                }
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }
    
    fun clearResults() {
        _searchResults.value = emptyList()
        _error.value = null
    }
}